<?php

namespace App\Http\Services\Api\V1\App\Webview;

use App\Http\Requests\App\PressIndexRequest;
use App\Models\Press\Press;
use App\Models\Press\PressCategory;
use App\Models\Products\Product;
use App\Models\Store\Store;
use App\Services\MobileApp\AppEnv;
use App\Services\Utils\ApiChecker;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;

class PressService
{
    use ApiChecker;

    /**
     * @param PressIndexRequest $request
     * @return LengthAwarePaginator
     */
    public function getPressList(PressIndexRequest $request)
    {
        $store_id = AppEnv::storeId();
        $press_category_id = $request->press_category_id;
        $product_id = $request->product_id;

        /** @var LengthAwarePaginator $presses */
        $presses = (new Press)->where('status', Press::PRESS_STATUS_ON)
            ->filterStoreId($store_id)
            ->filterPressCategoryId($press_category_id)
            ->filterProductId($product_id)
            ->oldest('sort_order') // 排序小优先
            ->latest('date_added') // 排序相同，最新优先
            ->with('filterPressDescriptionByLanguage')
            ->paginate($request->per_page ? : 10);

        $presses->getCollection()->transform(function(Press $press){
            $press->title = $press->filterPressDescriptionByLanguage->title ?? null;

            $press->addHidden('filterPressDescriptionByLanguage');

            return $press;
        });

        return $presses;
    }

    /**
     * @param $press_id
     * @param $store_id
     * @return array
     * @throws \Exception
     */
    public function getPressDetail($press_id, $store_id)
    {
        /** @var Press $press */
        $press = (new Press)->filterStoreId($store_id)
            ->where('status', Press::PRESS_STATUS_ON)
            ->where('press_id', $press_id)
            ->with('filterPressDescriptionByLanguage', 'pressProducts')
            ->first();

        $this->checkItemExist($press);

        $press->increment('hits');

        $product_ids = $press->pressProducts->pluck('product_id')->all() ?? [];
        $press->addHidden('pressProducts');

        $recommend_products = (new HomeService)->getRecommendProduct($product_ids, 1000);

        return compact('press', 'recommend_products');
    }
}